package com.chixing.controller;


import com.chixing.commons.ServerResponce;
import com.chixing.commons.ServerResponse;
import com.chixing.pojo.Coupon;
import com.chixing.pojo.Mycoupon;
import com.chixing.pojo.Users;
import com.chixing.service.ICartService;
import com.chixing.service.IMycouponService;
import com.chixing.service.IProductService;
import com.chixing.service.IUsersService;
import com.chixing.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService usersService;
    @Autowired
    private ICartService iCartService;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IMycouponService iMycouponService;

    /* 注册 */
    //根据号码进行 DB判断，是否已注册用户
    @PostMapping("checkTelno")
    public Boolean checkTelno(String userTelno){
        System.out.println("userTelno:" + userTelno);

        List<Users> usersList = usersService.getAll();
        System.out.println(usersList);

        if(usersList != null){ //有数据进行判断；无数据直接插入
            for(Users user: usersList){

                boolean nan = userTelno.equals(String.valueOf(user.getUserTelno()));
                System.out.println("nan:" + nan);

                if(nan)
                    return false; // 已注册 -- 前端提示 “此号码已注册账号！请直接登录！”
            }
        }
        return true; //未注册
    }

    //添加用户
    @PostMapping("save")
    public ServerResponse save(Users users, String userTelno, String userPwd){
        users.setUserNickname("用户" + UUID.randomUUID().toString().replace("-",""));
        users.setUserTelno(Long.valueOf(userTelno));
        users.setUserPwd(userPwd); //【加密！！！】
        return usersService.save(users);
    }

    /* 登录  */
    @PostMapping("login")
    public Object login(Users users, HttpServletRequest request, HttpServletResponse response){
        //        前端穿过来的加密密码
        System.out.println("前端加过密的密码："+users.getUserPwd());
//        后端MD5加密操作
        String password = users.getUserPwd();
        String md5Password = password + "mest";//后端加盐操作
        String finalPassword = DigestUtils.md5DigestAsHex(md5Password.getBytes());// 最终的 MD5 密码
        System.out.println("后端加过密的密码："+finalPassword);
        users.setUserPwd(finalPassword);

        ServerResponce result = usersService.login(users);
        System.out.println("4.controller result:" + result);
        Object data = null;
        if(result.getCode()== 200){
            System.out.println("5.customer controller 登录成功");
            data = result.getData();
            System.out.println("6.customer result data token:" + data);
        }
        return data;
    }

    @GetMapping("test1")
    public Map<String, Object> test1(HttpServletRequest request){

        //1.从头部获得token
        String token = request.getHeader("token");
        System.out.println(token);
        if(token!=null) {

            //2.解析 token，获得登录用户的信息
            Integer userId = TokenUtil.parseToken(token).getCustId();
            String custName = TokenUtil.parseToken(token).getCustName();
            System.out.println("userId:" + userId);
            System.out.println("custName:" + custName);

            //3. 获取用户购物车数量
            Integer userCartProductCount = iCartService.getUserCartProductCount(userId);

            //4.获得商品热数据
            Map<String, Object> map = new HashMap<>();
            map.put("custName", custName);
            map.put("userCartProductCount", userCartProductCount);
            return map;
        }
        return null;

    }

    //用户领取优惠券
    @GetMapping("usergetCoupon")
    public ServerResponce userGetCoupon(Coupon coupon, HttpServletRequest request){
//        从token中获取用户的ID
        String token = request.getHeader("token");
        Integer custId = TokenUtil.parseToken(token).getCustId();
//        获取优惠券的使用和到期时间
        LocalDateTime couponStartTime = coupon.getCouponStartTime();
        LocalDateTime couponEndTime = coupon.getCouponEndTime();

//        创建Mycoupon
        Mycoupon mycoupon = new Mycoupon();
        mycoupon.setMycouponNumber(UUID.randomUUID().toString());
        mycoupon.setMycouponStatus(1);
        mycoupon.setMycouponGetTime(LocalDate.now());
        mycoupon.setUserId(custId);
        mycoupon.setCouponId(coupon.getCouponId());
        Integer insert = iMycouponService.insert(mycoupon);
        if(insert>0){
            return ServerResponce.success("恭喜你领取优惠券成功",null);
        }
        return ServerResponce.fail("不好意思领取失败",null);
    }


}
